package apiUtils.apis;

import org.json.JSONException;

import java.io.IOException;

import apiUtils.APISHelper;
import apiUtils.CallBack;
import apiUtils.params.Params;
import appUtils.PayTokenException;
import io.reactivex.functions.Consumer;
import okhttp3.Call;

import static constant.ApiConstants.DOMAIN_NAME;

/**
 * 获取服务器时间
 */
public class GetDataTimeAPI extends APISHelper {
    private static final String tag = "GetDataTimeAPI";
    private static final String url = DOMAIN_NAME + "getServerTime";

    public void getServerTime(final Listener listener) {
        try {
            post(tag, url, new CallBack() {
                @Override
                public void onSuccess(Call call, String response) throws IOException {
                    if (null != response) {
                        long timeOffset = (Long.parseLong(response) - System.currentTimeMillis());
                        success(timeOffset, listener);
                    }
                }

                @Override
                public void onError(int code) {
                    failure(code, listener);
                }
            });
        } catch (JSONException e) {
            e.printStackTrace();
            failure(-1, listener);
            PayTokenException.getInstance().saveExceptionFile("GetDataTimeAPI post json error:"
                    + e.getMessage());
        }
    }

    private void success(final long timeOffset, final Listener listener) {
        subscribe(new Consumer<Integer>() {
            @Override
            public void accept(Integer integer) throws Exception {
                if (null != listener) {
                    listener.onSuccess(timeOffset);
                }
            }
        });
    }

    private void failure(final int code, final Listener listener) {
        subscribe(new Consumer<Integer>() {
            @Override
            public void accept(Integer integer) throws Exception {
                if (listener != null) {
                    listener.onFailure(code);
                }
            }
        });
    }

    @Override
    protected Params initParams() throws JSONException {
        return null;
    }

    public interface Listener {
        void onSuccess(long deltaTime);

        void onFailure(int code);
    }
}
